import { useEffect, useState } from "react";
import { Card, Input } from "antd";
import { useAddTask } from "../../utils/task";
import { useProjectIdInUrl, useTasksQueryKey } from "./util";

export const CreateTask = ({ kanbanId }: { kanbanId: number }) => {
    const [inputMode, setInputMode] = useState(false);
    const [name, setName] = useState('');

    const { mutateAsync: addTask } = useAddTask(useTasksQueryKey());

    const projectId = useProjectIdInUrl();

    const toggle = () => setInputMode((mode) => !mode);

    const onSubmit = async () => {
        await addTask({ projectId, kanbanId, name });
        setInputMode(false);
    }

    useEffect(() => {
        if (!inputMode) {
            setName("");
        }
    }, [inputMode]);

    if (!inputMode) {
        return <div onClick={toggle}>+创建事务</div>
    }

    return (
        <Card>
            <Input
                value={name}
                placeholder={'需要做些什么'}
                autoFocus={true}
                onChange={(evt) => setName(evt.target.value)}
                onBlur={toggle}
                onPressEnter={onSubmit}
            />
        </Card>
    )
}
